package org.kl.auditsupervision.web.fnd;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.kl.bf.entity.easyui.EasyuiGrid;
import org.kl.bf.entity.easyui.EasyuiTreeNode;
import org.kl.bf.entity.easyui.EasyuiUtils;
import org.kl.bf.utils.KLServlets;
import org.kl.bf.web.base.BasicController;
import org.kl.auditsupervision.entity.fnd.Org;
import org.kl.auditsupervision.service.fnd.OrgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.utils.Collections3;
import org.springside.modules.web.MediaTypes;

/**
 * @author Code Generator
 * @since 2015-09-09 10:59:57
 * @see 组织机构表 组织机构表
 */
@Controller
@RequestMapping(value = "/fnd/org")
public class OrgController extends BasicController {

	@Autowired
	private OrgService orgService;

	@RequiresPermissions(value = "org:list")
	@RequestMapping(method = RequestMethod.GET)
	public String list() {
		return "fnd/orgList";
	}

	// @RequiresPermissions(value = "org:list")
	@RequestMapping(value = "dataGrid", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String dataGrid(
			@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "rows", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "sort", defaultValue = "createTime") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType,
			Model model, ServletRequest request) {
		Map<String, Object> searchParams = KLServlets
				.getParametersStartingWith(request, SEARCH_PREFIX);
		Page<Org> org = orgService.getPage(searchParams, pageNumber, pageSize,
				sortType, orderType);
		List<Org> orgList=org.getContent();
		List<Org> newOrgList=new ArrayList<Org>();
		for(Org org1 :orgList){
			String superiorDeptName="";
			superiorDeptName=getParentOrgName(org1.getId(),"");
			org1.setSuperiorDeptName(superiorDeptName);
			newOrgList.add(org1);
		}
		return EasyuiUtils.buildEasyuiGridJsonString(newOrgList,
				(int) org.getTotalElements());
		/*return EasyuiUtils.buildEasyuiGridJsonString(org.getContent(),
				(int) org.getTotalElements());*/
	}
	
	@RequestMapping(value = "dataGridFilter", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String dataGridFilter(
			@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "rows", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "sort", defaultValue = "createTime") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType,
			Model model, ServletRequest request) {
		Map<String, Object> searchParams = KLServlets
				.getParametersStartingWith(request, SEARCH_PREFIX);
		String orgId="",allChildOrgId="";
		if(!isPermission("org"+":allQuery")){
			orgId=BasicController.getCurrentUserDeptId();
			orgId=orgService.getAllChildOrgId(orgId, allChildOrgId)+","+orgId;
			if(searchParams.containsKey("IN_id")){				
				searchParams.remove("IN_id");				
			}
			searchParams.put("IN_id",orgId);
		}else{
			
		}
		Page<Org> org = orgService.getPage(searchParams, pageNumber, pageSize,
				sortType, orderType);
		List<Org> orgList=org.getContent();
		List<Org> newOrgList=new ArrayList<Org>();
		for(Org org1 :orgList){
			String superiorDeptName="";
			superiorDeptName=getParentOrgName(org1.getId(),"");
			org1.setSuperiorDeptName(superiorDeptName);
			newOrgList.add(org1);
		}
		return EasyuiUtils.buildEasyuiGridJsonString(newOrgList,
				(int) org.getTotalElements());
		/*return EasyuiUtils.buildEasyuiGridJsonString(org.getContent(),
				(int) org.getTotalElements());*/
	}

	public String getParentOrgName(String id,String superiorDeptName){
		//String superiorDeptName="";
		Org org=orgService.getOne(id);
		if(StringUtils.isNotBlank(org.getParentOrgId())){
			Org parentOrg=orgService.getOne(org.getParentOrgId());
			if(StringUtils.isBlank(superiorDeptName)){
				superiorDeptName=parentOrg.getOrgName();
			}else{
				superiorDeptName=parentOrg.getOrgName()+"-"+superiorDeptName;
			}
			
			if(StringUtils.isNotBlank(parentOrg.getParentOrgId())){
				superiorDeptName=getParentOrgName(parentOrg.getId(),superiorDeptName);
			}
		}
		return superiorDeptName;
	}
	
	/*已把方法写在sevice层！！！！public String getAllParentOrgId(String id,String allParentOrgId){
		Org org=orgService.getOne(id);
		if(StringUtils.isNotBlank(org.getParentOrgId())){
			Org parentOrg=orgService.getOne(org.getParentOrgId());
			if(StringUtils.isBlank(allParentOrgId)){
				allParentOrgId=parentOrg.getParentOrgId();
			}else{
				allParentOrgId=parentOrg.getParentOrgId()+","+allParentOrgId;
			}
			
			if(StringUtils.isNotBlank(parentOrg.getParentOrgId())){
				allParentOrgId=getAllParentOrgId(parentOrg.getId(),allParentOrgId);
			}
		}
		return allParentOrgId;
	}
	
	public String getAllChildOrgId(String id,String allChildOrgId){
			List<Org> orgList=orgService.findByParentOrgId(id);
			for(Org org:orgList){
				if(StringUtils.isBlank(allChildOrgId)){
					allChildOrgId=org.getId();
				}else{
					allChildOrgId=org.getId()+","+allChildOrgId;
				}
				List<Org> orgChildList=orgService.findByParentOrgId(org.getId());
				if (Collections3.isNotEmpty(orgChildList)) {
					for(Org orgChild:orgChildList){
						allChildOrgId=getAllChildOrgId(orgChild.getId(),allChildOrgId);
					}
				}
			}
		
		return allChildOrgId;
	}*/
	
	public String getParentAndChildOrgId(String id){
		String allParentOrgId="",lastParentOrgId="";
		allParentOrgId=orgService.getAllParentOrgId(id, allParentOrgId);
		if(StringUtils.isNotBlank(allParentOrgId)){
			String[] idArray = StringUtils.split(allParentOrgId, ",");
			lastParentOrgId=idArray[0];
		}else{
			lastParentOrgId=id;
		}
		String allChildOrgId="";
		allChildOrgId=orgService.getAllChildOrgId(lastParentOrgId, allChildOrgId);
		String allId="";
		if(StringUtils.isNotBlank(allChildOrgId)){
			allId=lastParentOrgId+","+allChildOrgId;
		}else{
			allId=lastParentOrgId;
		}
		return allId;
}

	@RequiresPermissions(value = "org:list")
	@RequestMapping(value = "tree", method = RequestMethod.GET, produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String tree(
			@RequestParam(value = "id", defaultValue = "") String id,
			@RequestParam(value = "sort", defaultValue = "orgName") String sortType,
			@RequestParam(value = "order", defaultValue = "asc") String orderType,
			Model model, ServletRequest request) {
		List<Org> orgList = new ArrayList<Org>();
		// orgList = orgService.getAllOrganization();
		Map<String, Object> searchParams = KLServlets
				.getParametersStartingWith(request, SEARCH_PREFIX);
		orgList = orgService.searchAll(searchParams,sortType,orderType);
		/*
		 * if (StringUtils.isBlank(id)) { List<Organization> root =
		 * organizationService.findRoot(); organizationList =
		 * organizationService.getAllOrganization(); if (root != null) {
		 * organizationList.addAll(root); //
		 * System.out.println("结果是"+root.get(0).getOrgName()); }
		 * List<Organization> rootChildren =
		 * organizationService.findByOrganizationsParentOrgIdIn(Collections3
		 * .extractToList(root, "id"));
		 * 
		 * if (rootChildren != null) { organizationList.addAll(rootChildren); }
		 * } else { organizationList = organizationService.findByOrgNo(id); }
		 * 
		 * // list排序 Collections.sort(organizationList, new
		 * Comparator<Organization>() { public int compare(Organization arg0,
		 * Organization arg1) { return
		 * arg0.getOrgNo().compareTo(arg1.getOrgNo()); } });
		 */
		List<EasyuiTreeNode> plainTree = new ArrayList<EasyuiTreeNode>();
		for (Org org : orgList) {
			EasyuiTreeNode one = orgToTreeNode(org);
			plainTree.add(one);
		}

		String result = jsonMapper.toJson(plainTree);
		return result;
	}
	
	@RequiresPermissions(value = "org:list")
	@RequestMapping(value = "treeFilter", method = RequestMethod.GET, produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String treeFilter(
			@RequestParam(value = "id", defaultValue = "") String id,
			@RequestParam(value = "sort", defaultValue = "orgName") String sortType,
			@RequestParam(value = "order", defaultValue = "asc") String orderType,
			Model model, ServletRequest request) {
		List<Org> orgList = new ArrayList<Org>();
		// orgList = orgService.getAllOrganization();
		Map<String, Object> searchParams = KLServlets
				.getParametersStartingWith(request, SEARCH_PREFIX);
		String orgId="",allChildOrgId="";
		if(!isPermission("org"+":allQuery")){
			orgId=BasicController.getCurrentUserDeptId();
			orgId=orgService.getAllChildOrgId(orgId, allChildOrgId)+","+orgId;
			if(searchParams.containsKey("IN_id")){				
				searchParams.remove("IN_id");				
			}
			searchParams.put("IN_id",orgId);
		}else{
			
		}
		orgList = orgService.searchAll(searchParams,sortType,orderType);
		/*
		 * if (StringUtils.isBlank(id)) { List<Organization> root =
		 * organizationService.findRoot(); organizationList =
		 * organizationService.getAllOrganization(); if (root != null) {
		 * organizationList.addAll(root); //
		 * System.out.println("结果是"+root.get(0).getOrgName()); }
		 * List<Organization> rootChildren =
		 * organizationService.findByOrganizationsParentOrgIdIn(Collections3
		 * .extractToList(root, "id"));
		 * 
		 * if (rootChildren != null) { organizationList.addAll(rootChildren); }
		 * } else { organizationList = organizationService.findByOrgNo(id); }
		 * 
		 * // list排序 Collections.sort(organizationList, new
		 * Comparator<Organization>() { public int compare(Organization arg0,
		 * Organization arg1) { return
		 * arg0.getOrgNo().compareTo(arg1.getOrgNo()); } });
		 */
		List<EasyuiTreeNode> plainTree = new ArrayList<EasyuiTreeNode>();
		for (Org org : orgList) {
			EasyuiTreeNode one = orgToTreeNode(org);
			plainTree.add(one);
		}

		String result = jsonMapper.toJson(plainTree);
		return result;
	}

	@RequiresPermissions(value = "org:update")
	@RequestMapping(value = "update", method = RequestMethod.POST, produces = { MediaTypes.TEXT_HTML_UTF_8,
			MediaTypes.JSON_UTF_8 })
	@ResponseBody
	public String update(
			@Valid @ModelAttribute("org") Org org,
			@RequestParam(value = "detailInserted", defaultValue = "") String detailInserted,
			@RequestParam(value = "detailUpdated", defaultValue = "") String detailUpdated,
			@RequestParam(value = "detailDeleted", defaultValue = "") String detailDeleted,
			BindingResult result) {
		if (result.hasErrors()) {
			return ajaxMsg(bindingMsg(result), false, null);
		}
		try {
			if (org != null && StringUtils.isBlank(org.getId())) {
				if (StringUtils.isBlank(org.getParentOrgId())) {
					org.setOrgNo("000");
					org.setOrgName("新部门名称");
					
				} else {
					Org parentOrg=orgService.getOne(org.getParentOrgId());
					String orgNo=parentOrg.getOrgNo()+"-000";
					org.setOrgNo(orgNo);
					org.setOrgName("新部门或科室");
					// System.out.println("父节点为"+organization.getParentOrgId());
					// organization.setPbsNodeCode("00000");
				}
				org.setEnable(new BigDecimal(1));
			}
			List<Org> OrgList = orgService.findByOrgNo(org.getOrgNo());
			if (Collections3.isNotEmpty(OrgList)) {
				if (OrgList.size() > 1
						|| !OrgList.get(0).getId().equals(org.getId())) {
					return ajaxMsg("保存失败，机构编码" + org.getOrgNo() + "已经存在",
							false, null);
				}
			}
			if (StringUtils.isNotEmpty(org.getParentOrgId())) {
				OrgList = orgService.findById(org.getParentOrgId());
				System.out.println("测试" + OrgList.get(0).getOrgName());
				if (Collections3.isEmpty(OrgList)) {
					return ajaxMsg(
							"保存失败，" + org.getOrgNo() + "的父节点"
									+ org.getParentOrgId() + "不存在，请选中节点后再新增",
							false, null);
				}
			} else {
				org.setParentOrgId(null);
			}
			orgService.save(org, detailInserted, detailUpdated, detailDeleted);
			
			if(StringUtils.isBlank(org.getRootOrgId())){
				org.setRootOrgId(org.getId());
			}
			orgService.save(org,"","","");
			
			return ajaxMsg("保存成功", true, orgToTreeNode(org));
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("保存失败", false, null);
		}
	}

	/*
	 * @RequiresPermissions(value = "org:delete")
	 * 
	 * @RequestMapping(value = "delete/{id}", produces =
	 * MediaTypes.JAVASCRIPT_UTF_8)
	 * 
	 * @ResponseBody public String delete(@PathVariable("id") String id,
	 * RedirectAttributes redirectAttributes) { try { orgService.delete(id);
	 * return ajaxMsg("删除成功", true, null); } catch (Exception e) {
	 * e.printStackTrace(); return ajaxMsg("删除失败", false, null); } }
	 */

	@RequiresPermissions({ "org:delete" })
	@RequestMapping(value = "delete", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String multiDelete(
			@RequestParam(value = "ids", defaultValue = "") String ids) {
		try {
			if (StringUtils.isBlank(ids)) {
				return ajaxMsg("请先勾选需要删除的节点", false, null);
			}
			/*
			 * String[] idArray = StringUtils.split(ids, ","); for (String id :
			 * idArray) { if (StringUtils.isNotBlank(id)) { List<Post> postList
			 * = postService.findByOrganizationId(id); for (Post p : postList) {
			 * postService.deletePost(p.getId()); } } }
			 */
			int count = orgService.batchDeleteOrg(ids);
			return ajaxMsg("成功删除" + count + "条", true, null);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("删除失败:" + e.getMessage(), false, null);
		}
	}

	@RequiresPermissions("org:export")
	@RequestMapping(value = "excelExport", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String excelExport(
			@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType,
			Model model, ServletRequest request, HttpServletResponse response) {
		Map<String, Object> searchParams = KLServlets
				.getParametersStartingWith(request, SEARCH_PREFIX);
		List<Org> org = orgService.searchAll(searchParams, sortType, orderType);
		super.export(Org.class, response, org, "组织机构表");
		return null;
	}

	// 获取部门的信息
	@RequestMapping(value = "loadData", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String loadData() {
		String result = "";
		List<Org> users = orgService.getAll();
		EasyuiGrid grid = new EasyuiGrid();
		grid.setTotal((int) users.size());
		try {
			if (users.size() > 0) {

				grid.setRows(users);
				result = jsonMapper.toJson(grid);
			}
		} catch (Exception e) {
			ajaxMsg("失败:" + e.getMessage(), false, null);
		}

		return result;
	}

	private EasyuiTreeNode orgToTreeNode(Org org) {
		EasyuiTreeNode one = new EasyuiTreeNode();
		one.setId(org.getId());
		one.setText(org.getOrgNo() + "--" + org.getOrgName());
		one.setPid(org.getParentOrgId());
		Map<String, Object> attributes = new HashMap<String, Object>();
		attributes.put("id", org.getId());
		attributes.put("orgNo", org.getOrgNo());
		attributes.put("orgName", org.getOrgName());
		attributes.put("parentOrgId", org.getParentOrgId());
		attributes.put("zip", org.getZip());
		attributes.put("enable", org.getEnable());
		attributes.put("address", org.getAddress());
		attributes.put("description", org.getDescription());
		attributes.put("fax", org.getFax());
		attributes.put("phoneNumber", org.getPhoneNumber());
		attributes.put("rootOrgId", org.getRootOrgId());
		attributes.put("orgLevel", org.getOrgLevel());
		one.setAttributes(attributes);
		if(org.getEnable().compareTo( new BigDecimal("1"))!=0){
			one.setIconCls("icon-no");
		}

		if (StringUtils.isNotBlank(org.getParentOrgId())
				&& orgService.childrenCount(org.getOrgNo()) > 0) {
			one.setState("closed");
		}
		return one;
	}

	/**
	 * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2
	 * Preparable二次部分绑定的效果,先根据form的id从数据库查出Task对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
	 */
	@ModelAttribute
	public void init(
			@RequestParam(value = "id", defaultValue = "-1") String id,
			Model model) {
		if (!id.equals("-1")) {
			model.addAttribute("Org", orgService.getOne(id));
		}
	}

}
